<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminModel;
use Illuminate\Http\Request;
use App\Tools\Fun;

class AdminController extends Controller
{
    public function login(Request $request) {
        $username = $request->input('username');
        $password = $request->input('password');
        if (!$username || !$password) {
            return self::sendError('账户或密码为空', 401);
        }
        
        $password = Fun::encodePassword($password);
        $admin = AdminModel::where('name', $username)->where('password', $password)->first();
        if (!$admin) {
            return self::sendError('账户或密码错误', 401);
        }
        
        // $token = sha1($admin->id. time(). $admin->name);
        $token = 'f7d837565d1e4f92ec7c903118b5531b14ef0ecf'; // 测试用的token
        $admin->token = $token;
        $admin->save();

        return self::sendOk(['token' => $token], '登录成功', 200);
    }

    public function logout(Request $request) {
        $admin = $request->admin;
        if ($admin) {
            $admin->token = sha1($admin->id. time());
            $admin->save();
        }
        return self::sendOk([], '已退出登录', 200);
    }

    public function info(Request $request) {
               
        $admin = AdminModel::find($request->admin->id);
        $admin->roles = ['admin'];
        $admin->avatar = '';
        $admin->introduction = "I am a super administrator";
        unset($admin->password);
        return self::sendOk($admin);
    }
}
